package cn.wolfcode.mq;

import cn.wolfcode.service.IOrderInfoService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@RocketMQMessageListener(consumerGroup = "orderPeddingGroup",topic = MQConstant.ORDER_PEDDING_TOPIC)
public class OrderPeddingQueueListener implements RocketMQListener<OrderMessage> {
    @Autowired
    private IOrderInfoService orderInfoService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage msg) {
        String tag = ":";
        // 用来响应给前端
        OrderMQResult result = new OrderMQResult();
        result.setToken(msg.getToken());//往消息中设置token后续建立长链接通道需要用webSocket
        try{
            //进行秒杀创建订单的逻辑
            String orderNo = orderInfoService.doSeckill(msg.getTime(), msg.getSeckillId(), String.valueOf(msg.getUserPhone()));
            //秒杀订单创建成功
            result.setOrderNo(orderNo); //往消息通知中设置订单编号
            tag += MQConstant.ORDER_RESULT_SUCCESS_TAG;
            // 发送延时消息(10分钟)用于后续用户支付所需时间
            //Message<String> orderNoMsg = MessageBuilder.withPayload(orderNo).build();
            //rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC+tag,orderNoMsg,3000,MQConstant.ORDER_PAY_TIMEOUT_DELAY_LEVEL);
        }catch(Exception ex){
            ex.printStackTrace();
            //秒杀订单创建失败
            result.setCode(SeckillCodeMsg.SECKILL_ERROR.getCode());
            result.setMsg(SeckillCodeMsg.SECKILL_ERROR.getMsg());
            result.setTime(msg.getTime());//往消息设置秒杀场次  (订单创建失败情况进行预库存回补)
            result.setSeckillId(msg.getSeckillId());//往消息设置秒杀ID(订单创建失败情况进行预库存回补)
            tag += MQConstant.ORDER_RESULT_FAIL_TAG;
        }
        //无论成功还是失败都需要往MQ发送消息,用户消息通知(成功和失败的消息),失败情况进行预库存回补(失败的消息)
        // ORDER_RESULT_TOPIC:SUCCESS ===>成功消息
        // ORDER_RESULT_TOPIC:FAIL    ===>失败消息
        rocketMQTemplate.syncSend(MQConstant.ORDER_RESULT_TOPIC+tag,result);
    }
}
